package com.lh.api.interceptor;

import com.lh.api.annotation.NotRepeatRequest;
import com.lh.api.config.MyConstants;
import com.lh.common.utils.AssertUtil;
import com.lh.common.utils.Constant;
import com.lh.common.utils.IPUtils;
import com.lh.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName: RepeatRequestInterceptor
 * @Description: 防止重复提交调用接口(这里用一句话描述这个类的作用)
 * @author TangCai
 * @date 2017年5月27日 下午5:44:58
 *
 */
@Component
@Slf4j
public class RepeatRequestInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private RedisUtils redisUtils;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handMethod = (HandlerMethod)handler;
		NotRepeatRequest notRepeatRequest = handMethod.getMethodAnnotation(NotRepeatRequest.class);
		if(notRepeatRequest != null){
			String key = (String) request.getAttribute(MyConstants.RUQUEST_INFO_NAME);
			key = IPUtils.getIpAddr(request)+key;
			AssertUtil.assertNotFalse(redisUtils.hasKey(key), Constant.RESULT.FI1008, "Please do not resubmit, please refresh and try again");
			redisUtils.set(key, 1, 2);
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String key = (String) request.getAttribute(MyConstants.RUQUEST_INFO_NAME);
		key = IPUtils.getIpAddr(request)+key;
		redisUtils.delete(key);
	}
}
